import {
  delectPageById,
  delectUserById,
  editPageData,
  editUserData,
  newPageData,
  newUserData,
  postPageListData,
  postUsersListData
} from '@/service/main/system/system'
import { defineStore } from 'pinia'
import type { ISystemState } from './type'
import useMainStore from '../main'

const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    usersList: [],
    usersTotalCount: 0,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    // 获取用户列表
    async postUsersListAction(queryInfo: any) {
      const userListResult = await postUsersListData(queryInfo)
      const { totalCount, list } = userListResult.data
      this.usersList = list
      this.usersTotalCount = totalCount
    },
    // 删除用户
    async deleteUserByIdAction(id: number) {
      // 删除数据
      const delectResult = await delectUserById(id)
      // 重新获取列表数据
      this.postUsersListAction({ offset: 0, size: 10 })
    },
    // 新建用户
    async newUserDataAction(userInfo: any) {
      // 1.请求创建用户接口
      const newResults = await newUserData(userInfo)

      // 2.重新获取列表数据
      this.postUsersListAction({ offset: 0, size: 10 })
    },
    // 编辑用户
    async editUserDataAction(id: number, userInfo: any) {
      const editResult = await editUserData(id, userInfo)

      // 2.重新获取列表数据
      this.postUsersListAction({ offset: 0, size: 10 })
    },

    /*********************针对页面的增删改查 ***********************/
    // 获取列表
    async postPageListAction(pageName: string, queryInfo: any) {
      const pageListResult = await postPageListData(pageName, queryInfo)
      const { totalCount, list } = pageListResult.data
      this.pageList = list
      this.pageTotalCount = totalCount
    },
    // 删除数据
    async delectPageByIdAction(pageName: string, id: number) {
      const delectResult = await delectPageById(pageName, id)

      this.postPageListAction(pageName, { offset: 0, size: 10 })
    },
    // 新建数据
    async newPageDataAction(pageName: string, pageInfo: any) {
      const newResults = await newPageData(pageName, pageInfo)

      this.postPageListAction(pageName, { offset: 0, size: 10 })
      // 请求所有数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    // 编辑数据
    async editPageDataAction(pageName: string, id: number, pageInfo: any) {
      const editResults = await editPageData(pageName, id, pageInfo)

      this.postPageListAction(pageName, { offset: 0, size: 10 })
      // 请求所有数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    }
  }
})

export default useSystemStore
